// API基础URL
const API_BASE_URL = '/api';

// 通用请求函数
async function request(endpoint, options = {}) {
    try {
        // 获取JWT令牌
        const token = localStorage.getItem('token');
        
        // 设置请求头，如果有令牌就添加Authorization头
        const headers = {
            'Content-Type': 'application/json',
            ...(token && { 'Authorization': `Bearer ${token}` }),
            ...options.headers
        };

        console.log(`发送请求到: ${API_BASE_URL}${endpoint}`, {
            method: options.method || 'GET'
        });

        const response = await fetch(`${API_BASE_URL}${endpoint}`, {
            ...options,
            headers
        });

        let data;
        const contentType = response.headers.get('content-type');
        if (contentType && contentType.includes('application/json')) {
            data = await response.json();
        } else {
            data = { message: await response.text() };
        }

        if (!response.ok) {
            // 处理401错误，可能是令牌无效或过期
            if (response.status === 401) {
                console.error('认证失败:', data.message);
                // 如果不是登录页面，则清除令牌并重定向
                if (!window.location.pathname.includes('login.html')) {
                    // 清除本地存储的所有认证信息
                    localStorage.removeItem('token');
                    localStorage.removeItem('currentUser');
                    // 显示消息，然后重定向
                    alert('您的登录已过期，请重新登录');
                    window.location.href = '/public/login.html';
                    return null;
                }
            }
            
            throw new Error(data.message || '请求失败');
        }

        return data;
    } catch (error) {
        console.error('API请求错误:', error, '端点:', endpoint);
        throw error;
    }
}

// 认证相关API
const auth = {
    register: (userData) => request('/auth/register', {
        method: 'POST',
        body: JSON.stringify(userData)
    }),
    
    login: (credentials) => request('/auth/login', {
        method: 'POST',
        body: JSON.stringify(credentials)
    }),
    
    forgotPassword: (email) => request('/auth/forgot-password', {
        method: 'POST',
        body: JSON.stringify({ email })
    }),
    
    resetPassword: (data) => request('/auth/reset-password', {
        method: 'POST',
        body: JSON.stringify(data)
    })
};

// 名片夹相关API
const folders = {
    create: (folderData) => request('/cards/folders', {
        method: 'POST',
        body: JSON.stringify(folderData)
    }),
    
    getAll: () => request('/cards/folders'),
    
    getAllWithDetails: () => request('/cards/folders/details'),
    
    update: (id, folderData) => request(`/cards/folders/${id}`, {
        method: 'PUT',
        body: JSON.stringify(folderData)
    }),
    
    delete: (id) => request(`/cards/folders/${id}`, {
        method: 'DELETE'
    })
};

// 名片相关API
const cards = {
    create: (folderId, cardData) => request(`/cards/folders/${folderId}/cards`, {
        method: 'POST',
        body: JSON.stringify(cardData)
    }),
    
    getByFolder: (folderId) => request(`/cards/folders/${folderId}/cards`),
    
    getById: (id) => request(`/cards/${id}`),
    
    update: (id, cardData) => request(`/cards/${id}`, {
        method: 'PUT',
        body: JSON.stringify(cardData)
    }),
    
    delete: (id) => request(`/cards/${id}`, {
        method: 'DELETE'
    }),
    
    batchCreate: (cardsData) => request(`/cards/batch`, {
        method: 'POST',
        body: JSON.stringify({ data: cardsData })
    })
};

// 导出API对象
window.api = {
    auth,
    folders,
    cards
}; 